//
//  MNDExchangeAlertViewController.m
//  minidai
//
//  Created by 谭谭伟 on 17/5/16.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDExchangeAlertViewController.h"

@interface MNDExchangeAlertViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *intergelViewBottomConstraint;

@end

@implementation MNDExchangeAlertViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.confirmExchangeButton.layer.cornerRadius = 5;
    self.confirmExchangeButton.clipsToBounds = YES;
    self.alertContainView.transform = CGAffineTransformMakeScale(0.2, 0.2);
    
    WeakSelf(self);
    [[self.actualExchangeTextField rac_textSignal] subscribeNext:^(id x) {
        if (weakself.actualExchangeTextField.text.integerValue > weakself.myTotalScore.integerValue) {
            weakself.actualExchangeTextField.text  = weakself.myTotalScore;
        }
        //大于等于100积分时计算金钱
        if (weakself.actualExchangeTextField.text.integerValue >= 100 && weakself.actualExchangeTextField.text.integerValue <= 5000) {
            //计算公式
            float num = (weakself.actualExchangeTextField.text.integerValue-100)/100*0.1+1;
            float money = weakself.actualExchangeTextField.text.integerValue *num*0.01;
            weakself.tipLabel.hidden = NO;
            weakself.tipLabel.text = [NSString stringWithFormat:@"可兑现%.2f元",money];
        }
        
        if (weakself.actualExchangeTextField.text.integerValue > 5000) {
            weakself.actualExchangeTextField.text = @"5000";
        }

    }];
}

- (void)viewWillAppear:(BOOL)animated {
    
    
    [super viewWillAppear:animated];
    
    [UIView animateWithDuration:0.7
                          delay:0.0
         usingSpringWithDamping:0.5
          initialSpringVelocity:0.1
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         
                         self.alertContainView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0);
                     }
                     completion:^(BOOL finished) {
                         
                     }];
    [self registerForKeyboardNotifications];
}

- (void)registerForKeyboardNotifications
{
    //使用NSNotificationCenter 鍵盤出現時
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShown:)
                                                 name:UIKeyboardWillChangeFrameNotification object:nil];
    //使用NSNotificationCenter 鍵盤隐藏時
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

//实现当键盘出现的时候计算键盘的高度大小。用于输入框显示位置
- (void)keyboardWillShown:(NSNotification*)notification {
    
    NSDictionary *info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    float height = keyboardSize.height;
    //输入框位置动画加载
    [UIView animateWithDuration:duration animations:^{
        
        //如果输入框的高度低于键盘出现后的高度，视图就上升；
    if ((self.alertContainView.frame.size.height + self.alertContainView.frame.origin.y) > (self.view.frame.size.height - height)) {
        self.view.frame = CGRectMake(0, -height, self.view.frame.size.width, self.view.frame.size.height);
    }
    }];
}


- (void)keyboardWillBeHidden:(NSNotification *)notification{
    self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}

#pragma mark -点击确认兑换

- (IBAction)clickConfirmExchangeButton:(UIButton *)sender {
    
    if (self.actualExchangeTextField.text.integerValue < 100) {
        self.tipLabel.hidden = NO;
        self.tipLabel.text = @"兑换积分最少为100";
        
        return;
    }
    if (self.actualExchangeTextField.text.integerValue > 5000) {
        self.tipLabel.hidden = NO;
        self.tipLabel.text = @"兑换积分最多为5000";
        
        return;
    }
    //进行兑换
    [NetworkProgressHUD showHud];
        
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"case_value":self.actualExchangeTextField.text, @"user_code": user.user_code}];
    
    [APIManager sendRequestWithPath:API_EXCHANGE_SCORE parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD showHudMsg:@"兑换成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"dismissAlertVC" object:nil];
            });
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

#pragma mark -UITextFieldDelegate
//设置textfield输入内容
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
 
    if (textField == self.actualExchangeTextField) {
         return [self validateNumber:string];
    }
    
    return YES;
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
